import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import { loadEnv } from "vite";
import { resolve } from "path";
import { isDate } from "@vue/shared";
import { viteMockServe } from "vite-plugin-mock";
import { createSvg } from "./src/assets/icons/index";
import { convertToBoolean} from "./src/utils/utils"

// https://vitejs.dev/config/
export default ({ command, mode }) => {
  let debug = require("debug");
  var appDebug = debug("app");
  var apiDebug = debug("api");
  var mock = convertToBoolean(loadEnv(mode, process.cwd()).VITE_MOCK_ENABLED);
  // todo npm run dev 时 command 输出 serve，理解应该输出 dev
  appDebug("vite.config.ts", command, mode, mock, typeof mock);

  return defineConfig({
    plugins: [
      vue(),
      createSvg("./src/assets/icons/svg/"),
      viteMockServe({
        // mockPath: resolve(__dirname, "./mock"),
        mockPath: "./mock",
        supportTs: true,
        watchFiles: true,
        // 开发打包开关
        // localEnabled: mode === "development",
        localEnabled:
          convertToBoolean(loadEnv(mode, process.cwd()).VITE_MOCK_ENABLED) || false,
        // 生产打包开关
        prodEnabled: false,
        // 是否在控制台显示请求日志
        logger: true,
        //  这样可以控制关闭mock的时候不让mock打包到最终代码内
        injectCode: `
          import { setupProdMockServer } from './mock/mockProdServer';
          setupProdMockServer();
        `,
      }),
    ],
    server: {
      host: "127.0.0.1",
      // port: 4000,
      port: Number(loadEnv(mode, process.cwd()).VITE_APP_PORT),
      // 端口被占用则直接退出
      strictPort: true,
      https: false,
      // 开发服务器启动时自动在浏览器中打开应用
      open: true,
      proxy: {
        // 选项写法
        "/api": {
          // target: 'http://jsonplaceholder.typicode.com',
          target: loadEnv(mode, process.cwd()).VITE_API_URL,
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, ""),
        },
      },
      hmr: {
        overlay: false,
      },
    },
    resolve: {
      alias: {
        "@": resolve(__dirname, "./src"),
        // utils: resolve(__dirname, "./src/utils"),
      },
    },
    css: {
      preprocessorOptions: {
        scss: {
          additionalData:
            // '@import "@/assets/styles/global.scss"; @import "@/assets/styles/variables.scss";',
            '@import "@/assets/styles/index.scss"; ',
        },
      },
    },
    build: {
      // chunk 大小警告的限制（以 kbs 为单位）
      chunkSizeWarningLimit: 1500,
      rollupOptions: {
        output: {
          manualChunks(id) {
            if (id.includes("node_modules")) {
              return id
                .toString()
                .split("node_modules")[1]
                .split("/")[0]
                .toString();
            }
          },
        },
      },
    },
  });
};
